package guilayer;

import javax.swing.JPanel;
import javax.swing.JButton;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;

import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

import modellayer.Customer;
import modellayer.PartOrder;
import modellayer.Product;
import modellayer.SalesOrder;
import modellayer.Supplier;
import controllayer.*;
import dblayer.*;

/**
 * @author Gruppe 3
 */
public class NewOrderPanel extends JPanel {
	//private JScrollPane productScrollPane;
	//private JPanel produktPanel;
	
	private JTextField txtDate,textField,textField_1,txtAddress,
	                   txtZipCode,txtCity,txtPhoneNo,txtProductName,txtTotalPrice, txtCustomerID;
	private JTable productTable;
	private CustomerCtr customerCtr;
	private ProductCtr productCtr;
	private SupplierCtr supplierCtr;
	private SalesOrderCtr salesOrderCtr;
	private DBCustomer dbCus;
	private int customerId;
	private JPanel newOrderPanel;
	private SalesOrder salesOrder;
	private dblayer.DBSalesOrder dbSalesOrder;
	private JTextField txtAmount;
	private JTable addedProductTable;
	private JScrollPane addedProductScrollPane;
	
	private int customerID;

	/**
	 * Create the panel.
	 * @throws SQLException 
	 */
	public NewOrderPanel() throws SQLException {
		productCtr = new ProductCtr();
		customerCtr = new CustomerCtr();
		supplierCtr = new SupplierCtr();
		salesOrderCtr = new SalesOrderCtr();
		dbCus = new DBCustomer();
		dbSalesOrder = new DBSalesOrder();

		salesOrder = new SalesOrder();
		
		
		setLayout(new BorderLayout(0, 0));
		
		newOrderPanel = new JPanel();
		newOrderPanel.setBorder(new TitledBorder(null, "New order", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		add(newOrderPanel, BorderLayout.CENTER);
		newOrderPanel.setLayout(null);
		
		JButton btnNewButton = new JButton("Add Order");
		btnNewButton.setBounds(732, 429, 89, 23);
		newOrderPanel.add(btnNewButton);
		btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {
					addOrder();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        }
    });
		
		initOrderInfoPane(newOrderPanel);
		initCustomerInfoPane(newOrderPanel);	
		initProductPanel(newOrderPanel, "");
		initAddedProductsPanel(newOrderPanel);
	}

	/**
	 * Initialize the orderInfo Panel
	 * @param newOrderPanel
	 */
	private void initOrderInfoPane(JPanel newOrderPanel) {
		JPanel orderInformationPanel = new JPanel();
		orderInformationPanel.setBorder(new TitledBorder(null, "Order information", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		orderInformationPanel.setBounds(10, 23, 306, 122);
		newOrderPanel.add(orderInformationPanel);
		orderInformationPanel.setLayout(null);
		
		JLabel lblDate = new JLabel("Date:");
		lblDate.setBounds(10, 24, 80, 14);
		orderInformationPanel.add(lblDate);
		
		txtDate = new JTextField();
		txtDate.setBounds(100, 21, 180, 20);
		orderInformationPanel.add(txtDate);
		txtDate.setColumns(10);
		
		textField = new JTextField();
		textField.setColumns(10);
		textField.setBounds(100, 52, 180, 20);
		orderInformationPanel.add(textField);
		
		textField_1 = new JTextField();
		textField_1.setColumns(10);
		textField_1.setBounds(100, 83, 180, 20);
		orderInformationPanel.add(textField_1);
		
		JLabel lblDeliveryStatus = new JLabel("Delivery status:");
		lblDeliveryStatus.setBounds(10, 55, 80, 14);
		orderInformationPanel.add(lblDeliveryStatus);
		
		JLabel lblDeliveryDate = new JLabel("Delivery date:");
		lblDeliveryDate.setBounds(10, 86, 80, 14);
		orderInformationPanel.add(lblDeliveryDate);
	}
	
	/**
	 * Initialize CustomerInfo Panel
	 * @param newOrderPanel
	 */
	private void initCustomerInfoPane(JPanel newOrderPanel) {
		JPanel customerInfoPanel = new JPanel();
		customerInfoPanel.setBorder(new TitledBorder(null, "Customer information", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		customerInfoPanel.setBounds(326, 23, 495, 122);
		newOrderPanel.add(customerInfoPanel);
		customerInfoPanel.setLayout(null);
		
		JLabel lblName = new JLabel("Name:");
		lblName.setBounds(10, 23, 80, 14);
		customerInfoPanel.add(lblName);
		
		@SuppressWarnings({ "rawtypes", "unchecked" })
		final
		JComboBox comboBoxName = new JComboBox(customerCtr.customerToComboBox());
		comboBoxName.setBounds(100, 20, 110, 20);
		comboBoxName.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				Customer customer = customerCtr.getCustomer(comboBoxName.getSelectedItem().toString());
				txtAddress.setText(customer.getAddress());
				
				txtZipCode.setText(Integer.toString(customer.getZipCode()));
				
				txtCity.setText(customer.getCity().getCity());
				
				txtPhoneNo.setText(customer.getPhoneNo());
				
				txtCustomerID.setText(Integer.toString(customer.getCustomerID()));
								
			}
		});
		customerInfoPanel.add(comboBoxName);
		
		txtAddress = new JTextField();
		txtAddress.setColumns(10);
		txtAddress.setBounds(100, 51, 110, 20);
		txtAddress.setEditable(false);
		customerInfoPanel.add(txtAddress);
		
		JLabel lblAddress = new JLabel("Address:");
		lblAddress.setBounds(10, 54, 80, 14);
		customerInfoPanel.add(lblAddress);
		
		txtZipCode = new JTextField();
		txtZipCode.setBounds(100, 82, 110, 20);
		customerInfoPanel.add(txtZipCode);
		txtZipCode.setColumns(10);
		txtZipCode.setEditable(false);
		
		JLabel lblZipCode = new JLabel("Zip code:");
		lblZipCode.setBounds(10, 85, 80, 14);
		customerInfoPanel.add(lblZipCode);
		
		JLabel lblCity = new JLabel("City:");
		lblCity.setBounds(285, 23, 80, 14);
		customerInfoPanel.add(lblCity);
		
		txtCity = new JTextField();
		txtCity.setColumns(10);
		txtCity.setBounds(375, 20, 110, 20);
		txtCity.setEditable(false);
		customerInfoPanel.add(txtCity);
		
		JLabel lblPhoneNumber = new JLabel("Phone number:");
		lblPhoneNumber.setBounds(285, 54, 80, 14);
		customerInfoPanel.add(lblPhoneNumber);
		
		txtPhoneNo = new JTextField();
		txtPhoneNo.setColumns(10);
		txtPhoneNo.setBounds(375, 51, 110, 20);
		txtPhoneNo.setEditable(false);
		customerInfoPanel.add(txtPhoneNo);
		
		txtCustomerID = new JTextField();
		txtCustomerID.setVisible(false);
		customerInfoPanel.add(txtCustomerID);
		
	}
	
	/**
	 * Initialize Product Panel
	 * @param newOrderPanel
	 * @throws SQLException 
	 */
	private void initProductPanel(final JPanel newOrderPanel, String searchString) throws SQLException {
		
		if(searchString.isEmpty())
			searchString = "";
		
		JPanel produktPanel = new JPanel();
		produktPanel.setBorder(new TitledBorder(null, "Product", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		produktPanel.setBounds(10, 156, 396, 296);
		newOrderPanel.add(produktPanel);
		produktPanel.setLayout(null);

		JLabel lblSupplier = new JLabel("Supplier:");
		lblSupplier.setBounds(10, 24, 63, 14);
		produktPanel.add(lblSupplier);
		
		final JComboBox comboBoxSupplier = new JComboBox(supplierCtr.supplierToComboBox());
		comboBoxSupplier.setBounds(83, 21, 110, 20);
		comboBoxSupplier.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				Supplier supplier = supplierCtr.getSupplier((comboBoxSupplier.getSelectedItem().toString()));			
				
			}
		});
		produktPanel.add(comboBoxSupplier);
		
		JLabel lblCategory = new JLabel("Category:");
		lblCategory.setBounds(203, 24, 63, 14);
		produktPanel.add(lblCategory);
		
		JComboBox comboBoxCat = new JComboBox();
		comboBoxCat.setBounds(276, 21, 110, 20);
		produktPanel.add(comboBoxCat);
		
		JLabel lblProductName = new JLabel("Product name:");
		lblProductName.setBounds(10, 52, 84, 14);
		produktPanel.add(lblProductName);
		
		txtProductName = new JTextField();
		txtProductName.setColumns(10);
		txtProductName.setBounds(93, 49, 293, 20);
		produktPanel.add(txtProductName);
		
	
		
		int maxID = dbSalesOrder.getMaxID();
		
		String[][] data = productCtr.productToTableArray("");
		String[] column = {"ID", "Name", "Price", "Product type", "In stock"};
		
		
			final JTable productTable = new JTable(data, column){
	
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int row, int column) {                
	                return false;               
	        }
	    };
		
		productTable.getTableHeader().setReorderingAllowed(false);
		productTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		productTable.setFillsViewportHeight(true);
		productTable.setAutoCreateRowSorter(false);
		productTable.setVisible(true);
        productTable.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
            public void valueChanged(ListSelectionEvent event) {
            	try {
            		
            		//(Integer.parseInt(productTable.getValueAt(productTable.getSelectedRow(), 0).toString());
            	} catch(ArrayIndexOutOfBoundsException e) {
            	} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
        });

        JScrollPane productScrollPane = new JScrollPane(productTable);
		productScrollPane.setBounds(10, 78, 376, 179);
		produktPanel.add(productScrollPane);
		
		txtAmount = new JTextField();
		txtAmount.setBounds(224, 263, 44, 20);
		produktPanel.add(txtAmount);
		txtAmount.setColumns(10);
		
		JLabel lblNewLabel = new JLabel("Amount:");
		lblNewLabel.setBounds(168, 266, 46, 14);
		produktPanel.add(lblNewLabel);
		
		JButton btnAddToOrder = new JButton("Add to order");
		btnAddToOrder.setBounds(276, 262, 110, 23);
		btnAddToOrder.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				int amount = Integer.parseInt(txtAmount.getText());
				Product p;
				try {
					p = productCtr.findProduct(productTable.getSelectedRow());
					salesOrderCtr.addPartOrder(Integer.parseInt(txtAmount.getText()), p, salesOrder.getSalesOrderID(), salesOrder);
					updateAddedTable();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (NumberFormatException e) {

				}
			}
			
		});
		produktPanel.add(btnAddToOrder);
		
		
	}
	
	
	/**
	 * Initialize addedproducts panel
	 * @param newOrderPanel
	 * @throws SQLException 
	 */
	private void initAddedProductsPanel(JPanel newOrderPanel) throws SQLException {
		
		JPanel addedProductsPanel = new JPanel();
		addedProductsPanel.setBorder(new TitledBorder(null, "Added products", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		addedProductsPanel.setBounds(416, 156, 405, 262);
		newOrderPanel.add(addedProductsPanel);
		addedProductsPanel.setLayout(null);
		
		txtTotalPrice = new JTextField();
		txtTotalPrice.setColumns(10);
		txtTotalPrice.setBounds(302, 231, 93, 20);
		txtTotalPrice.setEditable(false);
		addedProductsPanel.add(txtTotalPrice);
		
		JLabel lblTotalPrice = new JLabel("Total price:");
		lblTotalPrice.setBounds(228, 234, 64, 14);
		addedProductsPanel.add(lblTotalPrice);

		
		String[][] data = salesOrderCtr.partOrderToTableArrayNewOrder(salesOrder);
		String[] column = {"Product", "Amount", "price"};

		
		addedProductTable = new JTable(data, column){
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int row, int column) {                
	                return false;               
	        }
	    };
		
	    addedProductTable.setBounds(10, 25, 385, 198);
		addedProductsPanel.add(addedProductTable);
		
		addedProductTable.getTableHeader().setReorderingAllowed(false);
		addedProductTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		addedProductTable.setFillsViewportHeight(true);
		addedProductTable.setAutoCreateRowSorter(false);
		addedProductTable.setVisible(true);
		
		
		addedProductScrollPane = new JScrollPane(addedProductTable);
		addedProductScrollPane.setBounds(10, 25, 385, 198);
		addedProductsPanel.add(addedProductScrollPane);
		
			
	}
	
	private void addOrder() throws SQLException {
		String date = txtDate.getText();
		String deliveryDate = textField.getText();
		String deliveryStatus = textField_1.getText();
		int customerID = Integer.parseInt(txtCustomerID.getText());
		
		if(!date.isEmpty() && !deliveryDate.isEmpty() && !deliveryStatus.isEmpty()) {
			salesOrder.setCustomerID(customerID);
			salesOrder.setDate(date);
			salesOrder.setDeliveryDate(deliveryDate);
			salesOrder.setDeliveryStatus(deliveryStatus);
			salesOrderCtr.createSalesOrder(salesOrder);
			
			int index = 0; 
		       while(index < salesOrder.getPartOrders().size())
		       {
		    	   PartOrder partOrder = salesOrder.getPartOrders().get(index);
		    	   
		    	   salesOrderCtr.createPartOrder(partOrder);
		    	   
		           index++;
		       }	
		       JOptionPane.showMessageDialog(this, "The order have been added", "Succes", JOptionPane.DEFAULT_OPTION);
		}else {
			JOptionPane.showMessageDialog(this, "1 or more fields are empty", "Error Message", JOptionPane.ERROR_MESSAGE);
		}
	}
	
	private void updateAddedTable() throws SQLException
	{
		  addedProductTable.removeAll();
		  this.remove(addedProductTable);
		  addedProductScrollPane.removeAll();
		  this.remove(addedProductScrollPane);
		  initAddedProductsPanel(newOrderPanel);
	}
}
